function guid() {
  function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }
  return [s4(), s4(), '_', s4(), '_', s4(), '_', s4(), '_', s4(), s4(), s4()].join('');
}

function getSessionId() {
  var id = sessionStorage.getItem('session_id');
  if (!id) {
    id = guid();
    sessionStorage.setItem('session_id', id);
  }
  return id;
}

function getRand(begin, end) {
  return Math.floor(Math.random() * (end - begin)) + begin;
}

function getRemember(Key) {
  return localStorage.getItem(Key);
}

function setRemember(Key, val) {
  return localStorage.setItem(Key, val);
}

function menuShow() {
  var menus = JSON.parse(getCookie('menus'));
  return menus;
}

function getCookie(sName) {
  var aCookie = document.cookie.split('; ');
  for (var i = 0; i < aCookie.length; i++) {
    var aCrumb = aCookie[i].split('=');
    if (sName === aCrumb[0]) {
      return unescape(aCrumb[1]);
    }
  }
  return null;
}

function todayShow() {
  var d = new Date();
  var yy = d.getFullYear();
  var mm = d.getMonth() + 1;
  var dd = d.getDate();
  var mytoday = yy + '年' + mm + '月' + dd + '日';
  return mytoday;
}

function weekShow() {
  var d = new Date();
  var weekday = new Array(7);
  weekday[0] = '星期天';
  weekday[1] = '星期一';
  weekday[2] = '星期二';
  weekday[3] = '星期三';
  weekday[4] = '星期四';
  weekday[5] = '星期五';
  weekday[6] = '星期六';
  return weekday[d.getDay()];
}

function clockShow() {
  var now = new Date();
  var hour = now.getHours();
  var minute = now.getMinutes();
  var second = now.getSeconds();
  var s = hour + ':' + minute + ':' + second + '';
  return s;
}

function showClock() {
  setTimeout(function() {
    this.clockShow();
  }, 1000);

}

function clearCookie() {
  var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
  if (keys) {
    for (var i = keys.length; i--;) {
      document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString();
    }
  }
}

function apiCall(method, path, params, cb) {
  var timeout = 300000; // 5 mins is enough
  $.ajax({
    timeout: timeout,
    url: path,
    method: method,
    cache: false,
    data: params,
    headers: {
      'x-session-id': getSessionId()
    },
    success: function(data) {
      cb(data);
    },
    error: function(xhr, status, data) {
      if (status == 'timeout') {
        return cb({ error: 'Query timeout after ' + (timeout / 1000) + 's' });
      }
      cb(jQuery.parseJSON(xhr.responseText));
    }
  });
}
